import axios from 'axios'
import baseUrl from './apiRoot.js'

// 实例化
const myAxios = axios.create({
    baseURL: baseUrl,
    timeout: 50000
});
myAxios.defaults.showFailToast = true;

// 添加请求拦截器
myAxios.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    if (!config.isAgent) {
        config.headers['access-token'] = config.headers['access-token'] ? config.headers['access-token'] : '270d2236a5bd4fc8aec9c0d61d405eb9';
    }
    return config;
}, error);

// 添加响应拦截器
myAxios.interceptors.response.use(response => {
    let success = true,
        resultMsg = '',
        data = '';
    if (response && response.status === 200) {
        if (response.data.errorCode === 100001) {
            resultMsg = '请重新登录';
            success = false;
        } else {
            if (response.data) {
                data = response.data.data || response.data || '';
                resultMsg = response.data.resultMsg || '';
                if (response.data.resultCode !== undefined && response.data.resultCode !== 1) {
                    success = false;
                    resultMsg = response.data.resultMsg || '接口失败';
                }
            }
        }
    } else if (response && response.status) {
        resultMsg = `请求状态错误码：${response.status}`;
        success = false;
    }
    if (!success && App && response.config.showFailToast) {
        //注释统一提示
        App.$toast.fail(resultMsg);
    }
    return {
        resultMsg,
        success,
        data
    };
}, error);

function error(error) {
    let resultMsg = `网络异常：`;
    if (error.response) {
        resultMsg = `${resultMsg} ${error.response.status} ${error.response.statusText}`;
    }
    return {
        resultMsg: resultMsg,
        success: false
    }
}

export default myAxios
